package io.xiyou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import io.xiyou.core.snowflake.SnowflakeIdWorker;
import io.xiyou.goods.api.IGoodsService;
import io.xiyou.goods.api.bo.CreateOrderBO;
import io.xiyou.goods.dao.mapper.GoodsMapper;
import io.xiyou.goods.dao.model.Goods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author 西柚
 */
@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${spring.kafka.topic-name}")
    private String topicName;

    /**
     * 创建订单
     *
     * @param createOrderBO
     */
    @Override
    public Long createOrder(CreateOrderBO createOrderBO) throws Exception {
        // 查询商品库存
        Goods goods = goodsMapper.selectById(createOrderBO.getGoodsId());
        if (Objects.isNull(goods)) {
            throw new Exception("商品不存在");
        } else if (goods.getStatus() != 2) {
            throw new Exception("商品状态异常");
        } else if (goods.getInventory().intValue() < createOrderBO.getCount()) {
            throw new Exception("商品库存不足");
        }

        // 减库存
        int count = goodsMapper.subtractInventory(createOrderBO.getGoodsId(), createOrderBO.getCount(), createOrderBO.getCreateBy(), new Date());
        if (count <= 0) {
            throw new Exception("商品库存不足");
        }

        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);

        // 生成订单号
        createOrderBO.setOrderCode(idWorker.nextId());
        createOrderBO.setOriginalPrice(goods.getOriginalPrice());
        createOrderBO.setPayPrice(goods.getSellPrice());
        createOrderBO.setDiscountsPrice(createOrderBO.getOriginalPrice().subtract(createOrderBO.getPayPrice()));

        // 异步创建订单
        this.kafkaTemplate.send(topicName, JSON.toJSONString(createOrderBO));

        log.info("发送成功:{}", JSON.toJSONString(createOrderBO));

        return createOrderBO.getOrderCode();
    }


}
